package com.school.sports.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.school.sports.entity.SystemConfig;
import com.school.sports.mapper.SystemConfigMapper;
import com.school.sports.service.SystemConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统配置服务实现类
 */
@Slf4j
@Service
public class SystemConfigServiceImpl extends ServiceImpl<SystemConfigMapper, SystemConfig> implements SystemConfigService {

    @Autowired
    private SystemConfigMapper systemConfigMapper;

    @Override
    public IPage<SystemConfig> getSystemConfigPage(Integer currentPage, Integer pageSize, SystemConfig systemConfig) {
        // 创建分页对象
        Page<SystemConfig> page = new Page<>(currentPage, pageSize);

        // 构建查询条件
        QueryWrapper<SystemConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        if (StringUtils.hasText(systemConfig.getConfigKey())) {
            queryWrapper.like("config_key", systemConfig.getConfigKey());
        }
        if (StringUtils.hasText(systemConfig.getConfigName())) {
            queryWrapper.like("config_name", systemConfig.getConfigName());
        }
        if (StringUtils.hasText(systemConfig.getConfigType())) {
            queryWrapper.eq("config_type", systemConfig.getConfigType());
        }
        if (systemConfig.getStatus() != null) {
            queryWrapper.eq("status", systemConfig.getStatus());
        }

        // 按配置类型、配置键排序
        queryWrapper.orderByAsc("config_type", "config_key");

        return this.page(page, queryWrapper);
    }

    @Override
    public String getConfigValue(String configKey) {
        SystemConfig config = systemConfigMapper.selectByConfigKey(configKey);
        return config != null ? config.getConfigValue() : null;
    }

    @Override
    public SystemConfig getConfig(String configKey) {
        return systemConfigMapper.selectByConfigKey(configKey);
    }

    @Override
    public List<SystemConfig> getConfigsByType(String configType) {
        return systemConfigMapper.selectByConfigType(configType);
    }

    @Override
    public boolean addSystemConfig(SystemConfig systemConfig, Long currentUserId) {
        // 检查配置键是否已存在
        if (checkConfigKeyExists(systemConfig.getConfigKey(), null)) {
            log.warn("配置键已存在：{}", systemConfig.getConfigKey());
            return false;
        }

        // 设置默认值
        systemConfig.setCreatedAt(LocalDateTime.now());
        systemConfig.setUpdatedAt(LocalDateTime.now());
        systemConfig.setCreatedBy(currentUserId);
        systemConfig.setUpdatedBy(currentUserId);
        systemConfig.setDeleted(0);

        if (systemConfig.getStatus() == null) {
            systemConfig.setStatus(1); // 默认启用
        }
        if (systemConfig.getIsBuiltIn() == null) {
            systemConfig.setIsBuiltIn(0); // 默认非内置
        }

        return this.save(systemConfig);
    }

    @Override
    public boolean updateSystemConfig(SystemConfig systemConfig, Long currentUserId) {
        // 检查配置是否存在
        SystemConfig existingConfig = this.getById(systemConfig.getId());
        if (existingConfig == null) {
            log.warn("配置不存在：{}", systemConfig.getId());
            return false;
        }

        // 内置配置不允许修改配置键
        if (existingConfig.getIsBuiltIn() == 1 &&
            !existingConfig.getConfigKey().equals(systemConfig.getConfigKey())) {
            log.warn("内置配置不允许修改配置键：{}", existingConfig.getConfigKey());
            return false;
        }

        // 检查配置键是否已存在（排除当前配置）
        if (checkConfigKeyExists(systemConfig.getConfigKey(), systemConfig.getId())) {
            log.warn("配置键已存在：{}", systemConfig.getConfigKey());
            return false;
        }

        // 设置更新信息
        systemConfig.setUpdatedAt(LocalDateTime.now());
        systemConfig.setUpdatedBy(currentUserId);

        return this.updateById(systemConfig);
    }

    @Override
    public boolean deleteSystemConfig(Long configId) {
        // 检查是否为内置配置
        SystemConfig config = this.getById(configId);
        if (config == null) {
            return false;
        }

        if (config.getIsBuiltIn() == 1) {
            log.warn("内置配置不允许删除：{}", config.getConfigKey());
            return false;
        }

        // 逻辑删除
        config.setDeleted(1);
        config.setUpdatedAt(LocalDateTime.now());
        return this.updateById(config);
    }

    @Override
    @Transactional
    public boolean batchDeleteSystemConfigs(List<Long> configIds) {
        List<SystemConfig> configs = this.listByIds(configIds);

        // 过滤掉内置配置
        List<SystemConfig> validConfigs = configs.stream()
                .filter(config -> config.getIsBuiltIn() != 1)
                .collect(Collectors.toList());

        if (validConfigs.isEmpty()) {
            return false;
        }

        // 批量逻辑删除
        LocalDateTime now = LocalDateTime.now();
        List<SystemConfig> updateConfigs = validConfigs.stream()
                .map(config -> {
                    config.setDeleted(1);
                    config.setUpdatedAt(now);
                    return config;
                })
                .collect(Collectors.toList());

        return this.updateBatchById(updateConfigs);
    }

    @Override
    public boolean updateConfigStatus(Long configId, Integer status, Long currentUserId) {
        SystemConfig config = new SystemConfig();
        config.setId(configId);
        config.setStatus(status);
        config.setUpdatedAt(LocalDateTime.now());
        config.setUpdatedBy(currentUserId);

        return this.updateById(config);
    }

    @Override
    public boolean checkConfigKeyExists(String configKey, Long excludeId) {
        return systemConfigMapper.countByConfigKey(configKey, excludeId) > 0;
    }

    @Override
    public boolean refreshConfigCache() {
        try {
            // 获取所有启用的配置
            List<SystemConfig> configs = systemConfigMapper.selectAllEnabledConfigs();

            // 这里可以添加缓存刷新逻辑，例如更新Redis缓存
            log.info("刷新系统配置缓存，共{}个配置", configs.size());

            return true;
        } catch (Exception e) {
            log.error("刷新配置缓存失败", e);
            return false;
        }
    }

    @Override
    public Map<String, String> getAllEnabledConfigs() {
        List<SystemConfig> configs = systemConfigMapper.selectAllEnabledConfigs();

        return configs.stream()
                .collect(Collectors.toMap(
                        SystemConfig::getConfigKey,
                        SystemConfig::getConfigValue,
                        (existing, replacement) -> existing // 处理重复键
                ));
    }

    @Override
    @Transactional
    public boolean batchUpdateConfigs(Map<String, String> configMap, Long currentUserId) {
        try {
            LocalDateTime now = LocalDateTime.now();

            for (Map.Entry<String, String> entry : configMap.entrySet()) {
                String configKey = entry.getKey();
                String configValue = entry.getValue();

                // 查找现有配置
                SystemConfig existingConfig = systemConfigMapper.selectByConfigKey(configKey);

                if (existingConfig != null) {
                    // 更新现有配置
                    existingConfig.setConfigValue(configValue);
                    existingConfig.setUpdatedAt(now);
                    existingConfig.setUpdatedBy(currentUserId);
                    this.updateById(existingConfig);
                } else {
                    // 创建新配置
                    SystemConfig newConfig = new SystemConfig();
                    newConfig.setConfigKey(configKey);
                    newConfig.setConfigValue(configValue);
                    newConfig.setConfigName(configKey);
                    newConfig.setConfigType("business");
                    newConfig.setIsBuiltIn(0);
                    newConfig.setStatus(1);
                    newConfig.setCreatedAt(now);
                    newConfig.setUpdatedAt(now);
                    newConfig.setCreatedBy(currentUserId);
                    newConfig.setUpdatedBy(currentUserId);
                    newConfig.setDeleted(0);
                    this.save(newConfig);
                }
            }

            return true;
        } catch (Exception e) {
            log.error("批量更新配置失败", e);
            return false;
        }
    }
}